﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gollie.DataTables;

namespace Gollie.Controls
{
	public partial class AgreeToDealTerms : BaseUserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			this.Populate();
		}

		private void Populate()
		{
			Count = 0;

			foreach (OrderBasketDataItem item in this.OrderBasketData)
			{
				this.CreateRow(item);
			}

			if (Count == 0)
				this.Visible = false;
		}

		private void CreateRow(OrderBasketDataItem item)
		{
			if (item.HasDescription() == false)
				return;

			Count++;

			TableRow tableRow = new TableRow();

			tableRow.Cells.Add(CreateCompanyCell(item));
			tableRow.Cells.Add(CreateCreditCell(item));
			tableRow.Cells.Add(CreatePriceCell(item));
			tableRow.Cells.Add(CreateDescriptionCell(item));
			tableRow.Cells.Add(CreateAgreeCell(item));

			this.tblDeals.Rows.Add(tableRow);
		}

		private TableCell CreateCompanyCell(OrderBasketDataItem item)
		{
			TableCell cell = CreateCell();
			cell.Text = item.Bedrijfsnaam;

			return cell;
		}

		private TableCell CreateCreditCell(OrderBasketDataItem item)
		{
			TableCell cell = CreateCell();

			cell.Text = ObjectFormatter.GetCurrencyString(item.TotalCredit);

			return cell;
		}

		private TableCell CreatePriceCell(OrderBasketDataItem item)
		{
			TableCell cell = CreateCell();

			cell.Text = ObjectFormatter.GetCurrencyString(item.TotalPrice);

			return cell;
		}

		private TableCell CreateDescriptionCell(OrderBasketDataItem item)
		{
			TableCell cell = CreateCell();
			cell.CssClass += " description";
			if (item.HasDescription())
				cell.Controls.Add(CreateDescriptionTextBox(item.Description));

			return cell;
		}

		private TableCell CreateAgreeCell(OrderBasketDataItem item)
		{
			TableCell cell = CreateCell();
			if (item.HasDescription())
			{
				cell.CssClass += " agreecb";
				CheckBox cbAgree = new CheckBox() { Text = "Akkoord", ID = "cbAgreeOnDealTerms" + Count.ToString(), ClientIDMode = System.Web.UI.ClientIDMode.Static };
				cbAgree.InputAttributes["class"] = "jqAgreeCb"; //using CssClass sets the class on a warpping <span>
				cell.Controls.Add(cbAgree);
			}

			return cell;
		}

		private TextBox CreateDescriptionTextBox(string comment)
		{
			TextBox tb = new TextBox();
			tb.TextMode = TextBoxMode.MultiLine;
			tb.Text = comment;
			tb.CssClass = "description-agree-on-pay";
			tb.Enabled = false;

			return tb;
		}

		private TableCell CreateCell()
		{
			return new TableCell() { CssClass = "agreedealterm" };
		}

		internal int Count { get; private set; }
	}
}